import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form,Select, Modal,  Divider,Row,Col,DatePicker} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;
const { Item } = Form;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
function handleChange(value) {
  console.log(`selected ${value}`);
}
class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '序号',
        dataIndex: 'id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '入库批次',
        dataIndex: 'compound_rkpc',
        editable: true,
      },
      {
        title: '粗提品数量',
        dataIndex: 'compound_ctpsl',
      
      },
      {
        title: '发酵批号',
        dataIndex: 'f_ph',
      },
      {
        title: '粗提品制备时间',
        dataIndex: 'compound_ctpzbsj',
      },
      {
        title: '粗提品制备人',
        dataIndex: 'ferment_ctpzbr',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width:400,
        render: (text, record) => (
          <span>
            <Button  type="dashed" onClick={() => this.showModal_view(record)}>
              查看
            </Button>
            <Divider type="vertical" />
            <Button type="dashed" onClick={() => this.showModal_edit(record)}>
              修改
            </Button>
            <Divider type="vertical" />
            <Button type="dashed" onClick={() => this.showModal_liufen}>
              粗体品编号
            </Button>
          </span>
        )
      },
    ];
    this.columns1 = [];
    this.columns2 = [ ]

    this.state = {
      dataSource: [ ],
      count: 0,

      selectedRowKeys: [], // Check here to configure the default column

      loading: false,
      loading_out: false,
  
      searchParams: {},

      newData: {},

      visible_add: false,
      visible_batch: false,

      visible_edit: false,
      editData: {},

      visible_liufen: false,

      visible_view:false,
      viewData: {},

    };
  }

  
  showModal_add = () => {
    this.setState({
      visible_add: true,
      newData: {}
    });
  };
  handleOk_add = e => {
    this.setState({
      visible_add: false,
    });
  };
  handleCancel_add = e => {
    this.setState({
      visible_add: false,
    });
  };

  // 查看
  showModal_view = ( record ) => {
    this.setState({
      visible_view: true,
      viewData: record
    });
  };
  handleOk_view = e => {
    this.setState({
      visible_view: false,
    });
  };
  handleCancel_view = e => {
    this.setState({
      visible_view: false,
    });
  };

  // 留份
  showModal_liufen = ( ) => {
    this.setState({
      visible_liufen: true,
    });
  };
  handleOk_liufen = e => {
    this.setState({
      visible_liufen: false,
    });
  };
  handleCancel_liufen = e => {
    this.setState({
      visible_liufen: false,
    });
  };

  showModal_batch = () => {
    this.setState({
      visible_batch: true,
    });
  };
  handleOk_batch = e => {
    this.setState({
      visible_batch: false,
    });
  };
  handleCancel_batch = e => {
    this.setState({
      visible_batch: false,
    });
  };

  showModal_edit = () => {
    this.setState({
      visible_edit: true,
    });
  };
  handleOk_edit = e => {
    this.setState({
      visible_edit: false,
    });
  };
  handleCancel_edit = e => {
    this.setState({
      visible_edit: false,
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  // 更新
  handleUpdate = () => {
    const url = global.api.crudeextractInfoOut + this.state.editData.id + '/';
    return global.updatedata.put(url, this.state.editData)
    .then(res => {  
      Modal.success({
        content: '更新成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '更新出错!',
      });
    })    
  }

  // 保存
  handleSave = row => {
    let record = this.state.newData;

    const url = global.api.crudeextractInfoOut;
    return global.network.post(url, record)
    .then(res => {

      this.loadData(1);

      Modal.success({
        content: '保存成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '保存出错!',
      });
    })

  };

  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   
 
  };

  loadData = (current = 1) => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.crudeextractInfoOut
    + "?compound_ckpc=" + (this.state.searchParams.compound_ckpc || "")
    + "&out_number=" + (this.state.searchParams.out_number || "")
    + "&compound_qyzl=" + (this.state.searchParams.compound_qyzl || "")
    + "&i_person=" + (this.state.searchParams.i_person || "")
    + "&out_time=" + (this.state.searchParams.out_time || "");
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: {}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 
  }
  componentDidMount() {
    this.loadData(1);
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    
    const { dataSource,loading, selectedRowKeys } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns1= this.columns1.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns2= this.columns2.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
         <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <Item label="出库批次">
            <Input onChange={e => this.state.searchParams.compound_ckpc = e.target.value} />
          </Item>
          <Item label="出库数量">
            <Input onChange={e => this.state.searchParams.out_number = e.target.value} />
          </Item>
          <Item label="筛选模型">
            <Input onChange={e => this.state.searchParams.compound_qyzl = e.target.value} />
          </Item>
          <Item label="取样人">
            <Input onChange={e => this.state.searchParams.i_person = e.target.value} />
          </Item>
          <Item label="取样时间">
            <DatePicker  format="YYYY-MM-DD" onChange={(date, dateStr) => this.state.searchParams.out_time = dateStr} style={{ width: "100%" }} />{" "}
          </Item>
          <Item wrapperCol={{ span: 10, offset: 5 }}>
            <Row guuter={16}>
              <Col span={5}>
              <Button type="primary" onClick={()=>this.loadData(1)} loading={this.state.loading}>
                  精确查询
                </Button>
              </Col>
              <Col span={5}>
              </Col>
              <Col span={5}>
                
              </Col>
              <Col span={5}>
                
              </Col>
            </Row>
          </Item>
        </Form>

        <div style={{marginTop: '50px',marginLeft: 16}}>
        <Button  disabled={!hasSelected} loading={this.state.loading_out} onClick={this.outToLocal} type="primary" >
          导出
        </Button>
        <Button  type="primary" onClick={this.showModal_add} style={{marginLeft: 16}}>
          流份出库
        </Button>
        <Button  type="primary" onClick={this.showModal_batch} style={{marginLeft: 16, display: 'none'}}>
          批量出库
        </Button>
         </div>
         <Modal
          title="粗提品出库"
          visible={this.state.visible_add}
          onOk={this.handleOk_add}
          onCancel={this.handleCancel_add}
        >
         <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
        >
           
              <Item label="粗提品编号">
                <Input onChange={e => this.state.newData.id = e.target.value} />
              </Item>
              <Item label="取样人">
                <Input onChange={e => this.state.newData.i_person = e.target.value} />
              </Item>
              <Item label="	发放人">
                <Input onChange={e => this.state.newData.worker = e.target.value} />
              </Item>
              <Item label="发放审核人">
                <Input onChange={e => this.state.newData.i_ffsh = e.target.value} />
              </Item>
              <Item label="	存放位置">
                <Input onChange={e => this.state.newData.store_place = e.target.value} />
              </Item>
              <Item label="出库时间">
                <DatePicker format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateStr) => this.state.newData.out_time = dateStr} style={{ width: "100%" }} />
              </Item>
              <Item label="出库数量">
                <Input onChange={e => this.state.newData.out_number = e.target.value} />
               </Item>
              <Item label="备注说明">
                <Input onChange={e => this.state.newData.remark = e.target.value} />
               </Item>
              <Item label="	粗提品编号">
                <Input onChange={e => this.state.newData.ctp_id  = e.target.value} />
               </Item>
              <Item label="发酵批号">
                <Input onChange={e => this.state.newData.f_ph = e.target.value} />
               </Item> 
              <Item label="入库批次">
                <Input onChange={e => this.state.newData.compound_rkpc = e.target.value} />
               </Item> 
              <Item label="	出库批次">
                <Input onChange={e => this.state.newData.compound_ckpc = e.target.value} />
               </Item> 
              <Item label="	粗提品出库数量">
                <Input onChange={e => this.state.newData.compound_ctpsl = e.target.value} />
               </Item>  
              <Item label="	筛选方法编号">
                <Input onChange={e => this.state.newData.m_id  = e.target.value} />
               </Item>  
              <Item label="	粗提品制备人">
                <Input onChange={e => this.state.newData.ferment_ctpzbr   = e.target.value} />
               </Item>  
              <Item label="	粗提品制备时间">
                <DatePicker format="YYYY-MM-DD HH:mm:ss" onChange={(date, dateStr) => this.state.newData.compound_ctpzbsj  = dateStr} style={{ width: "100%" }} />{" "}
              </Item>         

              <Item label="&nbsp;">
                <Button type="primary" loading={this.state.loading} onClick={this.handleSave}> 保存 </Button>          
              </Item>
            </Form>
        </Modal>
        <Modal
          title="批量出库"
          visible={this.state.visible_batch}
          onOk={this.handleOk_batch}
          onCancel={this.handleCancel_batch}
        >
        <Button  type="primary" style={{marginTop: '50px',marginLeft: 16}}>
          导出
        </Button>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns1}
          scroll={{ x: 3500}}
        />
        </Modal>
        <Modal
          title="查看"
          visible={this.state.visible_view}
          onOk={this.handleOk_view}
          onCancel={this.handleCancel_view}
        >
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
        >
            <div style={{ display: "flex" }}>
                <span style={{ flex: 1 }}>
                  <Item label="编号">
                    <Input defaultValue={this.state.viewData.id} />
                  </Item>
                  <Item label="取样人">
                    <Input defaultValue={this.state.viewData.i_person} />
                  </Item>
                  <Item label="发放人">
                    <Input defaultValue={this.state.viewData.worker} />
                  </Item>
                  <Item label="发放审核人">
                    <Input defaultValue={this.state.viewData.i_ffsh} />
                  </Item>
                  <Item label="出库时间">
                    <Input defaultValue={this.state.viewData.out_time} />
                  </Item>
                  <Item label="出库数量">
                    <Input defaultValue={this.state.viewData.out_number} />
                  </Item>
                  <Item label="存放位置">
                    <Input defaultValue={this.state.viewData.store_place} />
                  </Item>
                  <Item label="备注说明">
                    <Input defaultValue={this.state.viewData.remark} />
                  </Item>
                  <Item label="入库批次">
                    <Input defaultValue={this.state.viewData.compound_rkpc} />
                  </Item>
                  <Item label="发酵批号">
                    <Input defaultValue={this.state.viewData.f_ph } />
                  </Item>
                  <Item label="粗提品编号">
                    <Input defaultValue={this.state.viewData.ctp_id } />
                  </Item>
                  <Item label="入库粗提品数量">
                    <Input defaultValue={this.state.viewData.compound_ctpsl  } />
                  </Item>
                  <Item label="	粗提品制备时间">
                    <Input defaultValue={this.state.viewData.compound_ctpzbsj  } />
                  </Item>
                  <Item label="	粗提品制备人">
                    <Input defaultValue={this.state.viewData.ferment_ctpzbr  } />
                  </Item>
                </span>
              </div>
          </Form>
        </Modal>
        <Modal
          title="修改"
          visible={this.state.visible_edit}
          onOk={this.handleOk_edit}
          onCancel={this.handleCancel_edit}
        >
           <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
        >

                <Item label="编号">
                    <Input defaultValue={this.state.editData.id} readOnly />
                  </Item>
                  <Item label="取样人">
                    <Input defaultValue={this.state.editData.i_person} onChange={e => this.state.editData.i_person = e.target.value} />
                  </Item>
                  <Item label="	发放人">
                    <Input defaultValue={this.state.editData.worker} onChange={e => this.state.editData.worker = e.target.value} />
                  </Item>
                  <Item label="	发放审核人">
                    <Input defaultValue={this.state.editData.i_ffsh} onChange={e => this.state.editData.i_ffsh = e.target.value} />
                  </Item>
                  <Item label="出库时间">
                    <DatePicker  format="YYYY-MM-DD HH:mm:ss" defaultValue={moment(this.state.editData.out_time)} onChange={(date, dateStr) => this.state.editData.out_time = dateStr} style={{ width: "100%" }} />{" "}
                  </Item>
                  <Item label="	出库数量">
                    <Input defaultValue={this.state.editData.out_number} onChange={e => this.state.editData.out_number = e.target.value} />
                  </Item>
                  <Item label="存放位置">
                    <Input defaultValue={this.state.editData.store_place} onChange={e => this.state.editData.store_place = e.target.value} />
                  </Item>
                  <Item label="备注说明">
                    <Input defaultValue={this.state.editData.remark} onChange={e => this.state.editData.remark = e.target.value} />
                  </Item>
                  <Item label="入库批次">
                    <Input defaultValue={this.state.editData.compound_rkpc} onChange={e => this.state.editData.compound_rkpc = e.target.value} />
                  </Item>
                  <Item label="出库批次">
                    <Input defaultValue={this.state.editData.compound_ckpc} onChange={e => this.state.editData.compound_ckpc = e.target.value} />
                  </Item>
                  <Item label="发酵批号">
                    <Input defaultValue={this.state.editData.f_ph } onChange={e => this.state.editData.f_ph = e.target.value} />
                  </Item>
                  <Item label="粗提品编号">
                    <Input defaultValue={this.state.editData.ctp_id } onChange={e => this.state.editData.ctp_id = e.target.value} />
                  </Item>
                  <Item label="粗提品出库数量">
                    <Input defaultValue={this.state.editData.compound_ctpsl  } onChange={e => this.state.editData.compound_ctpsl = e.target.value} />
                  </Item>
                  <Item label="	粗提品制备时间">
                    <Input defaultValue={this.state.editData.compound_ctpzbsj  } onChange={e => this.state.editData.compound_ctpzbsj = e.target.value} />
                  </Item>
                  <Item label="	粗提品制备人">
                    <Input defaultValue={this.state.editData.ferment_ctpzbr  } onChange={e => this.state.editData.ferment_ctpzbr = e.target.value} />
                  </Item>

                  <Item label="&nbsp;">
                    <Button type="primary" loading={this.state.loading} onClick={this.handleUpdate}> 更新 </Button>          
                  </Item>                    
                
          </Form>
        </Modal>
        <Modal
          title="粗体品编号"
          visible={this.state.visible_liufen}
          onOk={this.handleOk_liufen}
          onCancel={this.handleCancel_liufen}
        >
           <Button  type="primary" style={{marginTop: 12,marginLeft: 16}}>
          导出
        </Button>
         <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns2}
          scroll={{ x: 4000, y: 300 }}
        />
        </Modal>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
        />
      </Content>
    );
  }
}

const ScreeningSaveInfo = Form.create()(EditableTable);
export default ScreeningSaveInfo;